package com.jn.gsondemo.views;

import android.os.Bundle;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.jn.geson_demo.R;
import com.jn.gsondemo.Adapter.MedalsAdapter;
import com.jn.gsondemo.entity.Medal;
import com.jn.gsondemo.utils.JsonUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;

public class MedalsListFragment extends Fragment {

    private RecyclerView medalsRecyclerView;
    private MedalsAdapter medalsAdapter;
    private ArrayList<Medal> medalList;

    public MedalsListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_medals_list, container, false);

        medalsRecyclerView = view.findViewById(R.id.medalsRecyclerView);
        medalsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        medalList = new ArrayList<>();
        medalList.clear(); // Ensure the list is empty before parsing
        parseJson();

        medalsAdapter = new MedalsAdapter(medalList);
        medalsRecyclerView.setAdapter(medalsAdapter);

        return view;
    }

    private void parseJson() {
        String jsonData = getJson("olympic.json");
        if (jsonData != null && !jsonData.isEmpty()) {
            try {
                JSONObject jsonObject = new JSONObject(jsonData);
                JSONArray medalsArray = jsonObject.optJSONObject("result").getJSONArray("medalsList");

                for (int i = 0; i < medalsArray.length(); i++) {
                    JSONObject medalObject = medalsArray.getJSONObject(i);
                    String rank = medalObject.getString("rank");
                    String countryName = medalObject.getString("countryname");
                    String gold = medalObject.getString("gold");
                    String silver = medalObject.getString("silver");
                    String bronze = medalObject.getString("bronze");

                    Medal medal = new Medal(rank, countryName, gold, silver, bronze);
                    medalList.add(medal);
                }
            } catch (Exception e) {
                Log.e("MedalsListFragment", "Error parsing JSON data", e);
            }
        } else {
            Log.e("MedalsListFragment", "JSON data is empty or not found.");
        }
    }

    private String getJson(String name) {
        try {
            return JsonUtils.getJsonFromAssets(getContext(), name);
        } catch (Exception e) {
            Log.e("MedalsListFragment", "Error reading JSON file", e);
            return null;
        }
    }
}